#! /usr/local/bin/python
#-*- coding: utf-8 -*-

"""Interface graphique pour la sauvegarde des parties.

_Fenêtre Toplevel modale_
"""

"""
Minesweeper 3K. Original implementation of the classic game of mines
for Python 3.
Copyright (C) 2010  Cedric Bonhomme

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.

Minesweeper 3K  Copyright (C) 2010  Cedric Bonhomme
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
"""

__author__ = "Jerome Hussenet, Cedric Bonhomme"
__date__ = "$Date: 2010/02/27 $"
__copyright__ = "Copyright (c) 2010 Jerome Hussenet, Copyright (c) 2010 Cedric Bonhomme"
__license__ = "GPL 3"

from tkinter import *
import tkinter.messagebox
import string

import sauvegarde

class SauvegardeGui(object):
    """Interface graphique pour la sauvegarde des parties.
    """
    def __init__(self, parent, grilleEtat, grilleMine, mines= 15, lon = 10, \
                            large = 10, temps = 0, niveau = 'debutant'):
        """Initialisation de l'interface.
        """
        self.frame = Toplevel()
        self.frame.title(_('Sauvegarde'))
        self.frame.resizable(height = False, width = False)

        self.grilleEtat = grilleEtat
        self.grilleMine = grilleMine
        self.mines, self.lon = mines, lon
        self.large = large
        self.temps = temps
        self.niveau = niveau

        Label(self.frame, text = _('Entrez votre mot de passe :')) \
                .grid(row=1, column = 0, padx = 50, pady = 10)

        self.code1 = Entry(self.frame)
        self.code1.configure(show='*')
        self.code1.grid(row = 2, column = 0, pady = 2)
        self.code1.focus_set()

        self.code2 = Entry(self.frame)
        self.code2.configure(show='*')
        self.code2.grid(row = 3, column = 0, pady = 2)

        self.checkEtat = IntVar(self.frame)
        self.check = Checkbutton(self.frame, text=_("Sans mot de passe"), variable = self.checkEtat)
        self.check.grid(row = 4, column = 0, pady = 2)
        self.check.bind("<ButtonPress-1>", self.checkClick)

        Button(self.frame, text=_("OK"), \
            command = self.test).grid(row = 5, column = 0, padx = 50, pady = 10)

        ## fixe le focus sur la fenêtre (obligatoire pour Windows)
        self.frame.focus_set()
        ## Force les évènements à aller sur cette fenêtre
        self.frame.grab_set()
        ## Pour que la fenêtre reste au-dessus de sa fenêtre parente
        self.frame.transient(parent)
        ## Affiche la fenêtre et attend sa fermeture
        self.frame.wait_window(self.frame)

    def test(self):
        """Vérifie le code.
        """
        code1 = ""
        if self.checkEtat.get() == 0:
            try:
                code1 = self.code1.get()
                code2 = self.code2.get()
            except:
                tkinter.messagebox.showerror(_('Erreur'), _("Erreur de saisie."))
                return
            finally:
                self.code1.delete(0, END)
                self.code2.delete(0, END)
                self.code1.focus_set()
            if code1 == "" or code2 == "":
                tkinter.messagebox.showerror(_('Erreur'), _("Saisissez votre mot de passe deux fois."))
                return
            if code1 != code2:
                tkinter.messagebox.showerror(_('Erreur'), _("Les saisies ne sont pas identiques."))
                return
            if len(code1) < 6:
                tkinter.messagebox.showerror(_('Erreur'), _("Le mot de passe doit avoir au moins six caractères."))
                return
            for caractere in code1:
                if caractere not in string.ascii_letters + string.digits:
                    tkinter.messagebox.showerror(_('Erreur'), _("Le mot de passe doit être alphanumérique."))
                    return
        self.sauvegarde(code1)

    def sauvegarde(self, code1):
        """Sauvegarde la partie.

        Saivegarde la partie via le module save,
        puis refermer la fenêtre modale de sauvegarde.
        """
        save = sauvegarde.Sauvegarde()
        save.sauvegarde(self.grilleEtat, self.grilleMine, temps = self.temps, \
            mines = self.mines, lon = self.lon, large = self.large, code = code1, niveau = self.niveau)
        save.write()
        self.frame.destroy()

    def checkClick(self, event):
        """Gestion de l'événement click gauche sur le bouton d'état.

        Les Entry sont désactivés si aucun
        mot de passe n'est utilisé.
        """
        self.code1.delete(0, END)
        self.code2.delete(0, END)
        self.code1.focus_set()
        if self.code1['state'] == 'normal':
            self.code1['state'] = 'disabled'
            self.code2['state'] = 'disabled'
        else:
            self.code1['state'] = 'normal'
            self.code2['state'] = 'normal'

if __name__ == '__main__':
    # Point d'entrée en exécution
    grilleEtat = [[0,1,2,0,1], [0,0,1,0,1], [2,1,0,0,1]]
    grilleMine = [['m','','','m',''], ['m','','','',''], ['','m','m','','']]
    sauv = SauvegardeGui(grilleEtat, grilleMine, mines= 15, lon = 10, large = 10, temps = 15, niveau='debutant')